package com.seamtop.cuber.core;

import com.seamtop.cuber.common.conf.CuberServerConfiger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by zongjunfeng on 2015/9/2.
 */
public class HBaseManager {

    private static final Logger LOG = LoggerFactory.getLogger(HBaseUtil.class);

    private static final String QUORUM = loadZookeeperServer();
    private static final String CLIENTPORT = "2181";
    private static Configuration conf = null;
    private static HConnection conn = null;
    /**
     * 获取全局唯一的Configuration实例
     * @return
     */
    public static synchronized Configuration getConfiguration()
    {
        if(conf == null)
        {
            conf =  HBaseConfiguration.create();
            conf.set("hbase.zookeeper.quorum", QUORUM);
            conf.set("hbase.zookeeper.property.clientPort", CLIENTPORT);
        }
        return conf;
    }

    private static String loadZookeeperServer(){
        String zookeeperCluster = CuberServerConfiger.serverConfigProperties.getProperty("zookeeper.cluster");
        String [] zooServers = zookeeperCluster.split(",");
        String zks = "";
        for(int i=0;i<zooServers.length;i++){
            String zookeeper = zooServers[i];
            zks += zookeeper.split(":")[0];
        }
        return zks;
    }

    /**
     * 获取全局唯一的HConnection实例
     * @return
     * @throws ZooKeeperConnectionException
     */
    public static synchronized HConnection getHConnection() throws ZooKeeperConnectionException,IOException
    {
        if(conn == null)
        {
            conn = HConnectionManager.createConnection(getConfiguration());
        }
        return conn;
    }
}
